const { parseMovieHTML, parseCelebrityHTML, parseCelebrityPhotosHTML, parseCelebritiesHTML } = require('./libs/parseHtmlMovie');
const { makeRequest } = require('./libs/gotRequest');
/**
 * 获取电影详情
 * @param {电影id} subject_id 
 * @returns 
 */
async function getMovieInfoFromOnlineById(subject_id) {
  try {
    const response = await makeRequest(`https://movie.douban.com/subject/${subject_id}/`);
    return parseMovieHTML(response, subject_id);
  } catch (error) {
    throw new Error('getMovieInfoFromOnlineById throws exception.', error);
  }
}

/**
 * 获取电影全部演员
 * @param {电影id} subject_id 
 * @returns 
 */
async function getMovieCelebritiesFromOnlineById(subject_id) {
  try {
    const response = await makeRequest(`https://movie.douban.com/subject/${subject_id}/celebrities`);
    return parseCelebritiesHTML(response, subject_id);
  } catch (error) {
    throw new Error('getMovieCelebritiesFromOnlineById throws exception.', error);
  }
}

/**
 * 获取演员详情
 * @param {演员id} subject_id 
 * @returns 
 */
async function getCelebrityInfoFromOnlineById(artist_id) {
  try {
    const response = await makeRequest(`https://movie.douban.com/celebrity/${artist_id}/`);
    return parseCelebrityHTML(response, artist_id);
  } catch (error) {
    throw new Error('getCelebrityInfoFromOnlineById throws exception.', error);
  }
}

/**
 * 获取演员全部图库
 * @param {演员id} artist_id 
 * @returns 
 */
async function getCelebrityPhotoFromOnlineById(artist_id) {
  try {
    let start = 0;
    const image_array = [];
    let total_image;
    let flag = true;
    do {
      const response = await makeRequest(`https://movie.douban.com/celebrity/${artist_id}/photos/?start=${start}`);
      const result = parseCelebrityPhotosHTML(response, artist_id);
      total_image = result.image_total;
      // 最多爬取500张
      total_image = total_image > 500 ? 500 : total_image;

      if (total_image > 0 && result.image_list.length > 0) {
        image_array.push(result.image_list);

        // 判断是否还有下一页
        if (start + 30 < total_image) {
          start += 30;
        } else {
          flag = false;
          break; // 如果当前页数已经超过或等于图片总数，则停止循环
        }
      } else {
        flag = false;
        break; // 如果没有获取到图片总数或者总数为0，则停止循环
      }
    } while (flag);
    if (image_array.length <= 0) {
      return {};
    }
    return {
      image_array: image_array.flat(),// 将多维数组展平为一维数组
      artist_id: artist_id
    };
  } catch (error) {
    throw new Error('getCelebrityPhotoFromOnlineById throws exception.', error);
  }
}
// 或者，使用 Promise（Node.js v14.18+）
// async function writeFileAsync(filePath, content) {
//   try {
//     await fs.promises.writeFile(filePath, content);
//     console.log('文件已成功写入');
//   } catch (err) {
//     console.error('写入文件时发生错误:', err);
//   }
// }


module.exports = {
  getMovieInfoFromOnlineById,
  getCelebrityInfoFromOnlineById,
  getCelebrityPhotoFromOnlineById,
  getMovieCelebritiesFromOnlineById
};